/**
 * 
 */
package com.xpec.c4.game.login.async2;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ms.player.Player;
import com.xpec.c4.db.dao.PlayerDAO;
import com.xpec.c4.game.datamanager.ResultNo;
import com.xpec.c4.game.utility.GUID;
import com.xpec.c4.service.module.common.PlayerCommonInfoManager;
import com.xpec.c4.service.module.task.TaskAsyncCommand;

/**
 * @author TW15010
 *
 */
public class DoAfterLoadPlayerAsync extends TaskAsyncCommand {
	/** log4j object */
	private static final Log log = LogFactory.getLog(DoAfterLoadPlayerAsync.class);

	/**
	 * 要載入的 player guid
	 */
	private GUID loadPlayerId;
	
	/**
	 * 這個 player 的 session id
	 */
	private GUID sessionId;

	/**
	 * 從 db 載入的 player data
	 */
	private Player loadPlayer;

	/**
	 * 處理結果
	 * 
	 * @see com.xpec.c4.game.datamanager.ResultNo
	 */
	private int resultCode;

	/**
	 * 
	 * @param loadPlayerId
	 * @param sessionId
	 */
	public void initial(GUID loadPlayerId, GUID sessionId) {
		this.loadPlayerId = loadPlayerId;
		this.key = loadPlayerId;
		this.sessionId = sessionId;
	}

	@Override
	public void asyncExecute() throws Exception {
		// TODO kevin jb verify
		try {
			loadPlayer = PlayerDAO.loadPlayerFromRedis(loadPlayerId);

			if (sessionId != null) {
				String platform = PlayerCommonInfoManager.getInstance().getLoginPlatformBySessionId(sessionId);
				loadPlayer.setLastLoginPlatform(platform);
				loadPlayer.setSessionID(sessionId);
			}

			loadPlayer.clearUpdatedAttrList();
			
		} catch (Exception e) {
			if (log.isErrorEnabled()) {
				log.error("get player fail.", e);
			}
			
			resultCode = ResultNo.DB_OPERATION_FAILED;
			return;
		}

		if (loadPlayer == null) {
			if (log.isErrorEnabled()) {
				log.error(this.getClass().getSimpleName() + "load Player data fail, g:" + loadPlayerId);
			}
			
			resultCode = ResultNo.DATA_NOT_FOUND;
			return;
		}
		
		resultCode = ResultNo.OK;
	}

	@Override
	public void execute() throws Exception {
	}

	public GUID getLoadPlayerId() {
		return loadPlayerId;
	}

	public void setLoadPlayerId(GUID loadPlayerId) {
		this.loadPlayerId = loadPlayerId;
	}

	public Player getLoadPlayer() {
		return loadPlayer;
	}

	public int getResultCode() {
		return resultCode;
	}
}
